package mil.af.amc.adpetracker.web.actions.EquipmentItem;

import mil.af.amc.adpetracker.web.actions.AbstractAction;
import mil.af.amc.adpetracker.service.EquipmentItemService;
import mil.af.amc.adpetracker.service.ServiceException;
import org.apache.struts.action.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This action unassigns a User from a piece of equipment, instead of unassigning a piece of
 * equipment from a user. The distinction depends on what the focus is: if you are viewing a piece
 * of equipment, you'll want to unassign the user from it. However, if you are viewing a User,
 * you'll want to unassign the equipment from them.
 *
 * This method keeps me from having to have some bastardized switch or string comparison to decide
 * where to forward to next.
 *
 * @author TSgt Jason Ferguson
 */

public class UnassignUserFromEquipmentAction extends AbstractAction {

    private EquipmentItemService equipmentItemService;

    public void setEquipmentItemService(EquipmentItemService equipmentItemService) {
        this.equipmentItemService = equipmentItemService;
    }

    @Override
    public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

        DynaActionForm form = (DynaActionForm) actionForm;
        int itemId = (Integer) form.get("itemId");

        try {
            equipmentItemService.unassignItem(itemId);
        } catch (ServiceException e) {
            ActionMessage message = new ActionMessage(e.getKey());
            saveError(httpServletRequest, message);
        }

        return actionMapping.getInputForward();
    }
}
